// middleware/cors.go
package middleware

import (
	"fmt"
	"net/http"
	"strings"

	"github.com/gin-gonic/gin"
)

// CORSOptions CORS 配置选项
type CORSOptions struct {
	AllowOrigins     []string
	AllowMethods     []string
	AllowHeaders     []string
	AllowCredentials bool
	MaxAge           int
}

// DefaultCORSOptions 默认 CORS 配置
var DefaultCORSOptions = CORSOptions{
	AllowOrigins:     []string{"*"},
	AllowMethods:     []string{"GET", "POST", "PUT", "DELETE", "OPTIONS"},
	AllowHeaders:     []string{"Origin", "Content-Type", "Accept", "Authorization"},
	AllowCredentials: true,
	MaxAge:           1728000, // 20天
}

// CORSMiddleware 返回一个处理 CORS 请求的中间件
func CORSMiddleware() gin.HandlerFunc {
	return CORSMiddlewareWithOptions(DefaultCORSOptions)
}

// CORSMiddlewareWithOptions 返回一个使用自定义选项的 CORS 中间件
func CORSMiddlewareWithOptions(options CORSOptions) gin.HandlerFunc {
	return func(c *gin.Context) {
		// 设置允许的来源
		for _, origin := range options.AllowOrigins {
			if origin == "*" {
				c.Writer.Header().Set("Access-Control-Allow-Origin", "*")
				break
			}
			if origin == c.Request.Header.Get("Origin") {
				c.Writer.Header().Set("Access-Control-Allow-Origin", origin)
				break
			}
		}

		// 设置其他 CORS 头
		c.Writer.Header().Set("Access-Control-Allow-Methods", strings.Join(options.AllowMethods, ","))
		c.Writer.Header().Set("Access-Control-Allow-Headers", strings.Join(options.AllowHeaders, ","))
		c.Writer.Header().Set("Access-Control-Allow-Credentials", fmt.Sprintf("%v", options.AllowCredentials))

		// 设置预检查请求的缓存时间
		if options.MaxAge > 0 {
			c.Writer.Header().Set("Access-Control-Max-Age", fmt.Sprintf("%d", options.MaxAge))
		}

		// 处理预检查请求
		if c.Request.Method == "OPTIONS" {
			c.AbortWithStatus(http.StatusNoContent)
			return
		}

		// 继续处理请求
		c.Next()
	}
}
